import json
import os
import unicodedata
import re



class FileHandler:
    """处理文件操作"""

    def __init__(self, search_query):
        self.directory = "scrapy_results"
        self.filename = f"{self.directory}/CNKI_{search_query}.json"
        os.makedirs(self.directory, exist_ok=True)

    def store_references(self, title, references):
        """
        存储参考文献信息
        """
        data = self.load_data()
        title = json.dumps(title, ensure_ascii=False)[1:-1]
        data.setdefault(title, []).extend(references)
        with open(self.filename, "w", encoding="utf-8") as file:
            json.dump(data, file, ensure_ascii=False)
            file.flush()

    def check_if_exists(self, title):
        """
        检查文献是否已经存在
        """
        data = self.load_data()
        return title in data and data[title] and len(data[title]) > 0

    def clean_invalid_chars(self, text):
        """
        清理无效字符
        """
        cleaned_text = "".join(
            char for char in text if unicodedata.category(char) != "Cn"
        )
        return (
            cleaned_text.replace(" ", "")
            if not re.search(r"[a-zA-Z]", cleaned_text)
            else cleaned_text
        )

    def load_data(self):
        """
        加载JSON数据
        """
        try:
            with open(self.filename, "r", encoding="utf-8") as f:
                return json.load(f)
        except (FileNotFoundError, json.JSONDecodeError):
            return {}

    def store_article_info(self, title, article_info, references):
        """
        存储文献信息至本地JSON文件
        """
        data = self.load_data()
        title = json.dumps(title, ensure_ascii=False)[1:-1]

        if title not in data or not isinstance(data[title], dict):
            data[title] = {"article_info": article_info, "references": []}

        data[title]["references"].extend(references)

        with open(self.filename, "w", encoding="utf-8") as f:
            json.dump(data, f, ensure_ascii=False, indent=2)
            f.flush()
